<template>
  <div>
    <div class="flex justify-center ">


      <el-form ref="ruleFormRef" class="flex flex-col  w-1/4 mt-[30vh]" :model="ruleForm" status-icon :rules="rules"
        label-width="auto">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="用户名" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" placeholder="密码" type="password" autocomplete="off" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登陆
          </el-button>

        </el-form-item>
      </el-form>


    </div>
  </div>
</template>

<script lang="ts" setup>

import type { FormInstance } from 'element-plus'
import { loginApi } from '@/api/index'
const ruleFormRef = ref<FormInstance>() // 获取form组件的引用

import type { ruleFormType, loginResponse } from '@/type/userType'

// import {useUserStore} from '@/stores/user'

//  const {setUserInfo} =     useUserStore()

import useValidate from './useValidate';

import {
  reactive,
  ref,
  ElMessage,
  router,
} from '../use'
//  表单数据
const ruleForm = reactive<ruleFormType>({
  username: '',
  password: ''
})
const { rules } = useValidate(ruleForm)


import createRoutes from '@/createRoutes'
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) return

    console.log(ruleForm);

    loginApi<loginResponse>(ruleForm).then(({ data }) => {

      if (data.code === 0) {

        ElMessage({
          message: data.msg,
          type: 'success',
        })

        // eslint-disable-next-line prefer-const
        let {token='',tokenExpired=''} = data
        tokenExpired = String(tokenExpired)


         localStorage.setItem('token',token)
         localStorage.setItem('tokenExpired',tokenExpired)

         createRoutes(router,function () {
          router.replace('/home')
         })



      }
    })


  })
}

</script>
